package com.cndym.utils;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;

/**
 * 作者: 邓玉明
 * 日期: 2010-10-1
 * 时间: 14:44:51
 * qq: 757579248
 * email: cndym@163.com
 */
public class SignAtureHelper {
    public static String sign(Map params, String privateKey) {
        Properties properties = new Properties();

        for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            Object value = params.get(name);

            if (name == null || name.equalsIgnoreCase("sign")
                    || name.equalsIgnoreCase("sign_type")) {
                continue;
            }

            properties.setProperty(name, value.toString());

        }

        String content = getSignatureContent(properties);
        return sign(content, privateKey);
    }

    public static String getSignatureContent(Properties properties) {
        StringBuffer content = new StringBuffer();
        List keys = new ArrayList(properties.keySet());
        Collections.sort(keys);

        for (int i = 0; i < keys.size(); i++) {
            String key = (String) keys.get(i);
            String value = properties.getProperty(key);
            content.append((i == 0 ? "" : "&") + key + "=" + value);
        }

        return content.toString();
    }

    public static String sign(String content, String privateKey) {
        if (privateKey == null) {
            return null;
        }
        String signBefore = content + privateKey;

        return Md5.Md5(signBefore);

    }

    public static final String SIGN_ALGORITHMS = "SHA1WithRSA";

    /**
     * RSA验签名检查
     *
     * @param content   待签名数据
     * @param sign      签名值
     * @param publicKey 支付宝公钥
     * @return 布尔值
     */
    public static boolean doCheck(String content, String sign, String publicKey) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decode(publicKey);
            PublicKey pubKey = keyFactory
                    .generatePublic(new X509EncodedKeySpec(encodedKey));

            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGN_ALGORITHMS);

            signature.initVerify(pubKey);
            signature.update(content.getBytes("utf-8"));

            boolean bverify = signature.verify(Base64.decode(sign));
            return bverify;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }


    public static void main(String [] args){
        String verifyData = "notify_data=<notify><seller_email>miaoqing@zch168.net</seller_email><partner>2088701406173485</partner><payment_type>1</payment_type><buyer_email>tianshi.2008@163.com</buyer_email><trade_no>2013012957330814</trade_no><buyer_id>2088002034034145</buyer_id><quantity>1</quantity><total_fee>1.00</total_fee><use_coupon>N</use_coupon><is_total_fee_adjust>Y</is_total_fee_adjust><price>1.00</price><out_trade_no>00497488517460568116</out_trade_no><gmt_create>2013-01-29 16:59:00</gmt_create><seller_id>2088701406173485</seller_id><subject>支付宝充值</subject><trade_status>WAIT_BUYER_PAY</trade_status><discount>0.00</discount></notify>";
        String sign = "auRfSRqFCPlmzhn0Uwgs0feOabQ7n6egbTgm7ubUBqs1z+4Do78l74Ax/yT/c4N5dRXOnasaykcEjsGv2LsO/xjkb9yQ3hO38Zcv4C6hMiQkhc7dLxAYTVuBxwwTiZKylZIFxb0XCYxDLFqRFtpwp2SEt67+d7lIz4JUJS655wg=";
        System.out.println(SignAtureHelper.doCheck(verifyData,sign,FillConfigUtils.getValue("ALIPAY_PUBLIC_KEY")));
    }
}
